package com.zky.controller;


import cn.hutool.core.lang.UUID;
import com.zky.dao.CattleDao;
import com.zky.domain.dto.CattleRequestDto;
import com.zky.domain.po.Cattle;
import com.zky.domain.po.PageResult;
import com.zky.domain.po.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("cattle")
@Api(tags = "奶牛相关接口")
@RequiredArgsConstructor
public class CattleController {

    private final CattleDao cattleDao;

    @ApiOperation("获取列表")
    @GetMapping
    public Result getAllCattleByRequest(CattleRequestDto cattleRequestDto) {
        List<Cattle> res = new ArrayList<>();
        List<Cattle> finalCattles = new ArrayList<>();
        List<Cattle> allCattle = cattleDao.getAllCattle();
        //先检索出来符合条件的item
        for (Cattle cattle : allCattle) {
            if(cattleRequestDto.getId()!=null&&!cattle.getId().equals(cattleRequestDto.getId())) {
                continue;
            }
            if(cattleRequestDto.getBreed()!=null&&!cattleRequestDto.getBreed().isEmpty() &&!cattle.getBreed().equals(cattleRequestDto.getBreed())) {
                continue;
            }
            res.add(cattle);
        }
        //开始手动分页
        int start = (cattleRequestDto.getPageNo()-1)*cattleRequestDto.getPageSize();
        for(int i=start;i<start+cattleRequestDto.getPageSize();i++) {
            if(i<res.size()) {
                finalCattles.add(res.get(i));
            }
            else{
                break;
            }
        }
        return PageResult.of(finalCattles,res.size());
    }

    @PostMapping()
    public Result addCattle(@RequestBody Cattle cattle) {
        long id = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
        cattle.setId(id);
        cattleDao.addCattle(cattle);
        return Result.ok();
    }
}
